import cv2
import numpy as np
import matplotlib.pyplot as plt

# 加载人脸图像
image = cv2.imread('1.jpg')
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# 将图像转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 使用不同边缘算子进行边缘检测
edges_canny = cv2.Canny(gray, 100, 200)
edges_sobel_x = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3)
edges_sobel_y = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3)
edges_sobel = cv2.Sobel(gray, cv2.CV_64F, 1, 1, ksize=3)
edges_prewitt_x = cv2.filter2D(gray, -1, np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]], dtype=np.float32))
edges_prewitt_y = cv2.filter2D(gray, -1, np.array([[-1, -1, -1], [0, 0, 0], [1, 1, 1]], dtype=np.float32))
edges_prewitt = cv2.addWeighted(edges_prewitt_x, 0.5, edges_prewitt_y, 0.5, 0)

# 显示结果
fig, axes = plt.subplots(2, 4, figsize=(16, 8))
axes[0, 0].imshow(image_rgb)
axes[0, 0].set_title('Original Image')
axes[0, 0].axis('off')

axes[0, 1].imshow(edges_canny, cmap='gray')
axes[0, 1].set_title('Canny')
axes[0, 1].axis('off')

axes[0, 2].imshow(edges_sobel_x, cmap='gray')
axes[0, 2].set_title('Sobel X')
axes[0, 2].axis('off')

axes[0, 3].imshow(edges_sobel_y, cmap='gray')
axes[0, 3].set_title('Sobel Y')
axes[0, 3].axis('off')

axes[1, 0].imshow(edges_sobel, cmap='gray')
axes[1, 0].set_title('Sobel')
axes[1, 0].axis('off')

axes[1, 1].imshow(edges_prewitt_x, cmap='gray')
axes[1, 1].set_title('Prewitt X')
axes[1, 1].axis('off')

axes[1, 2].imshow(edges_prewitt_y, cmap='gray')
axes[1, 2].set_title('Prewitt Y')
axes[1, 2].axis('off')

axes[1, 3].imshow(edges_prewitt, cmap='gray')
axes[1, 3].set_title('Prewitt')
axes[1, 3].axis('off')

plt.tight_layout()
plt.show()
